import tkinter as tk
from tkinter import ttk

# 职业表
jobs = {'农民': 0, '工人': 0, '教师': 0, '学生': 0}
# 病历表
data = [{'name': '张三', 'flu': '1', 'hot': '0', 'job': '农民'}]

# 显示表
def show_data():
    # 先删除
    for i in table.get_children():
        table.delete(i)
    # 再添加
    for item in data:
        table.insert('', 'end', values=(item['name'], item['flu'], item['hot'], item['job']))

def add_data():
    name = name_entry.get()
    if name != "":
        flu = 1 if flu_checkbox.instate(['selected']) else 0
        hot = 1 if hot_checkbox.instate(['selected']) else 0
        job = job_combobox.get()

        json = {'name': name, 'flu': flu, 'hot': hot, 'job': job}
        data.append(json)
        show_data()
        bayes_naive()
# 朴素贝叶斯
def bayes_naive():
    # 患者总数
    size = len(data)

    # 感冒患者数量
    flu = sum(int(item['flu']) for item in data)
    print(flu)
    # 发烧患者数量
    hot = sum(int(item['hot']) for item in data)
    # 既感冒又发烧患者数量
    flu_hot = sum(int(item['flu']) and int(item['hot']) for item in data)
    html = ''
    # 遍历所有职业
    for key in jobs:
        # 职业出现的概率
        job = sum(1 for item in data if item['job'] == key)
        # 拉普拉斯平滑
        if job == 0:
            job = 0.01
        # 该职业感冒的概率
        flu_job = sum(1 for item in data if item['job'] == key and item['flu'] == '1')
        # 朴素贝叶斯公式
        # P(感冒|发烧、农民)= P(感冒) x P(发烧|感冒) x P(农民|感冒) / P(发烧) x P(农民)
        print(key,flu,flu_hot,flu_job,hot,job)
        p = ((flu / size) * (flu_hot / flu) * (flu_job / flu)) / ((hot / size) * (job / size))
        html += f'发烧的{key}感冒的概率{p}\n'

    title_label.config(text=html)
    print(f'总数{size}, 感冒{flu}, 发烧{hot}, 发烧又感冒{flu_hot}')


root = tk.Tk()
root.title("朴素贝叶斯")

# 表单区
frame1 = ttk.Frame(root)
frame1.pack()
ttk.Label(frame1, text="姓名:").pack(side="left")
name_entry = ttk.Entry(frame1)
name_entry.pack(side="left")

ttk.Label(frame1, text="感冒:").pack(side="left")
flu_checkbox = ttk.Checkbutton(frame1)
flu_checkbox.pack(side="left")

ttk.Label(frame1, text="发烧:").pack(side="left")
hot_checkbox = ttk.Checkbutton(frame1)
hot_checkbox.pack(side="left")

ttk.Label(frame1, text="职业:").pack(side="left")
job_combobox = ttk.Combobox(frame1, values=list(jobs.keys()))
job_combobox.pack(side="left")
# 按钮
ttk.Button(frame1, text="增加", command=add_data).pack(side="left")

# 显示区
title_label = tk.Label(root, text="不同职业感冒的概率:", justify=tk.LEFT)
title_label.pack()

 # 创建病历表
table = ttk.Treeview(root, columns=('姓名', '感冒', '发烧', '职业'), show='headings')
table.heading('姓名', text='姓名')
table.heading('感冒', text='感冒')
table.heading('发烧', text='发烧')
table.heading('职业', text='职业')
table.pack(fill='both', expand=True)

show_data()

root.mainloop()